package coe.pumbaa


import org.springframework.dao.DataIntegrityViolationException
import grails.plugins.springsecurity.Secured


class UserController {
    def springSecurityService
    def stringManagerService
    def authenticationManagerService
    static allowedMethods = [save: "POST", update: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }
    def blockUser(){
        def user = User.get(params.id)
        if( user ){
            user.enabled = false
            user.status = User.BLOCK_USER
            user.save(fluse:true)
        }
        render (template: "block", model: [user:user])
    }
    def unblockUser(){
        def user = User.get(params.id)
        if( user ){
            user.enabled = true
            user.status = User.ACTIVE_USER
            user.save(fluse:true)
        }
        render (template: "block", model: [user:user])
    }
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def list() {
        if(springSecurityService.currentUser.role.level <= 0){
            params.max = Math.min(params.max ? params.int('max') : 10, 100)
            
            
            def userList = User.withCriteria(){
                ne ("status", User.PENDING_USER)
                order("id", "asc")
            }
            
            //def userList = User.findAllByStatus(User.ACTIVE_USER,params)
                [userInstanceList: authenticationManagerService.filteredWithMaxAndOffset(userList, params), userInstanceTotal: userList.size(),navigation:[pos:"manage_user"]]
        }else{
            flash.warning = "You are not admin."
            redirect(controller:'home',action:'index')
        }
    }
    
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def userProfile() {
        [navigation:[pos:'user',action:'userProfile']]
    }
    
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def subscription() {
        def user = springSecurityService.currentUser
        def postInstanceTotal = stringManagerService.getMemberListInString(user.subscribe).size()
        def postInstanceList = authenticationManagerService.getPostSubList(user,params)
        [postInstanceList:postInstanceList,postInstanceTotal:postInstanceTotal,navigation:[pos:'user',action:'subscription']]
    }
    
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def listOfRequest(){
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        def userList = User.findAllByStatus(User.PENDING_USER,params)
        [userRequestList: userList, userRequestTotal: User.findAllByStatus(User.PENDING_USER).size(),navigation:[pos:"manage_user"]]
    }
    
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def accept(){
        def user = User.get(params.id)       
        if(!user){
            flash.error = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
        }
        user.voter = stringManagerService.addObjectInToString(springSecurityService.currentUser,user.voter)
        if(springSecurityService.currentUser.role.level <= 1){
            user.status = User.ACTIVE_USER
            user.enabled = true
        }else{
            if(user.voter.size() >= 5){
                user.status = User.ACTIVE_USER
                user.enabled = true
            }
        }
        
        user.save(flush:true)
        if(springSecurityService.isLoggedIn() && (springSecurityService.currentUser.role.level == 0)){
            redirect(action:'list')
        }else{
            redirect(controller:'home',action: "index")
        }
    }
    
    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def reject(){
        def user = User.get(params.id)
        if(!user){
            flash.error = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
        }
        user.rejecter = stringManagerService.addObjectInToString(springSecurityService.currentUser,user.rejecter)
        if(springSecurityService.currentUser.role.level <= 0){
            user.delete(flush:true)
        }else{
            if(user.rejecter.size() >= 20){
                user.delete(flush:true)
            }
        }
        if(springSecurityService.isLoggedIn() && (springSecurityService.currentUser.role.level == 0)){
            redirect(action:'list')
        }else{
            redirect(controller:'home',action: "index")
        }
    }

    def create() {
        def roleList = Role.withCriteria(params){
            ne ("level", 0)
        }
        [userInstance: new User(params), roleList: roleList]
    }

    def save() {
        def userInstance = new User(params)
        userInstance.status = User.PENDING_USER
        userInstance.enabled = false
        userInstance.voter = ""
        def uploadedFile = request.getFile('avatar')
        println "Class: ${uploadedFile.class}"
        println "Name: ${uploadedFile.name}"
        println "OriginalFileName: ${uploadedFile.originalFilename}"
        println "Size: ${uploadedFile.size}"
        println "ContentType: ${uploadedFile.contentType}"
        if (!userInstance.save(flush: true)) {
            userInstance.validate()
            flash.error = "Error! Check your input."
            render(view: "create", model: [userInstance: userInstance])
            return
        }
        flash.success = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        if(springSecurityService.isLoggedIn() && (springSecurityService.currentUser.role.level == 0)){
            redirect(action:'list')
        }else{
            redirect(controller:'home',action: "index")
        }
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def edit() {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.error = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance, navigation: [pos: 'user']]
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def update() {
        def userInstance = User.get(params.id)
        userInstance.properties = params
        if (!userInstance.save(flush: true)) {
            flash.error = "Error! Check your input."
            render(view: "edit", model: [userInstance: userInstance])
            return
        }
        flash.success = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "list")
    }

    @Secured(['IS_AUTHENTICATED_REMEMBERED'])
    def delete() {
        if(springSecurityService.currentUser.role.level <= 1){
            def userInstance = User.get(params.id)
            if(!userInstance.delete(flush: true)){
                flash.error = "Error! Can not delete."
            }else{
                flash.success = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
            }
            redirect(action: "list")
        }else{
            flash.warning = "You are not admin."
            redirect(controller:'home',action:'index')
        }
    }
    
    def viewImage() {
        def user = User.get( params.id )
        OutputStream out = response.getOutputStream();
        if(!springSecurityService.isLoggedIn() || (user.avatar == null)){
            user = User.findByEmail("anonymous")
        }
        out.write(user.avatar)
        out.close();
    }
}
